package dao;

import model.MemberUser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Objects;

public class MemberUserDao {
    Database database = new Database();
    String user_table = "member_user";
    ArrayList<String> arrayList = new ArrayList<String>();
    public static final Logger logger = LogManager.getLogger(MemberUserDao.class);

    public boolean Login(MemberUser memberUser) throws SQLException {
        String login = "select username from " + user_table + " where username ='" + memberUser.getUsername() + "' and password ='" + memberUser.getPassword() + "'";
        logger.info("Login SQL:" + login);
        try (ResultSet resultSet = database.query(login)) {
            try {
                if (resultSet.next()) {
                    logger.info("Now user " + memberUser.getUsername() + " is login!");
                    return true;
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }

    /**
     * 用于登录时产生用户ID
     *
     * @param memberUser 用户登录信息对象
     * @return 用户ID
     * @throws SQLException SQL Error
     */
    public int getUserId(MemberUser memberUser) throws SQLException {
        String userId = "select id from " + user_table + " where username ='" + memberUser.getUsername() + "' and password ='" + memberUser.getPassword() + "'";
        logger.info("userId SQL:" + userId);
        try (ResultSet resultSet = database.query(userId)) {
            while (resultSet.next()) {
                memberUser.setId(resultSet.getInt("id"));
            }
        }
        return memberUser.getId();
    }

    /**
     * 注册用户通用功能
     *
     * @param memberUser 用户对象
     * @param user_table 用户表
     * @param database   数据库对象
     * @return boolean
     * @throws SQLException Error
     */
    static boolean createUser(MemberUser memberUser, String user_table, Database database) throws SQLException {
        try {
            String createUser = "insert into " + user_table + " (email,username,password,state) values(?,?,?,?)";
            PreparedStatement preparedStatement = database.getPreparedStatement(createUser);
            preparedStatement.setString(1, memberUser.getEmail());
            preparedStatement.setString(2, memberUser.getUsername());
            preparedStatement.setString(3, memberUser.getPassword());
            preparedStatement.setInt(4, memberUser.getState());
            logger.info("createUser SQL:" + preparedStatement);
            preparedStatement.executeUpdate();
            logger.info("user:" + memberUser.getUsername() + "create success!");
            return true;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 注册用户功能
     *
     * @param memberUser 用户基本资料
     * @return 注册成功与否
     * @throws SQLException SQL Error
     */
    public boolean regUser(MemberUser memberUser) throws SQLException {
        if (memberUser.getUsername() == null || memberUser.getPassword() == null) {
            return false;
        } else {
            logger.info("regUser:" + memberUser.getUsername());
            memberUser.setState(1); // 默认启用
            return createUser(memberUser, user_table, database);
        }
    }

    /**
     * 获取用户资料
     *
     * @param userId 用户ID
     * @return 用户资料数组对象
     * @throws SQLException SQL Error
     */
    public ArrayList<String> getUserProfile(int userId) throws SQLException {
        try {
            String userInfo = "select username,email from " + user_table + " where id =" + userId;
            String userProfile = "select username,email from member_profile where id =" + userId;
            logger.info("userInfo SQL:" + userInfo);
            logger.info("userProfile SQL:" + userProfile);
            try (ResultSet resultSet = database.query(userInfo)) {
                arrayList.add(resultSet.getString("username"));
                arrayList.add(resultSet.getString("email"));
            }
            try (ResultSet resultSet = database.query(userProfile)) {
                arrayList.add(resultSet.getString("name"));
                arrayList.add(resultSet.getString("tel"));
            }
            logger.info(arrayList);
            return arrayList;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 用户修改密码方法
     *
     * @param memberUser 用户对象（必须包含id）
     * @return boolean
     */
    public boolean userChangePassword(MemberUser memberUser) {
        if (memberUser.getId() != 0) {
            try {
                String getPassword = "select password from " + user_table + " where id = " + memberUser.getId();
                logger.info("getPassword SQL:"+getPassword);
                String userPassword = null;
                try (ResultSet resultSet = database.query(getPassword)) {
                    if (resultSet.next()) {
                        userPassword = resultSet.getString("password");
                        logger.info("userPassword = " + userPassword);
                    }
                }
                if (Objects.equals(userPassword, memberUser.getPassword())) {
                    logger.info("start to change user password!");
                    String newPassword = "update " + user_table + " set password = ? where id = " + memberUser.getId();
                    PreparedStatement preparedStatement = database.getPreparedStatement(newPassword);
                    preparedStatement.setString(1, memberUser.getNewPassword());
                    logger.info("userChangePassword by id SQL:" + preparedStatement);
                    preparedStatement.executeUpdate();
                    logger.info("user id:" + memberUser.getId() + " change password success!");
                    return true;
                }
            } catch (SQLException e) {
                logger.error(e);
                throw new RuntimeException(e);
            }
        }
        return false;
    }
}
